package com.xizi.consumer;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.util.Arrays;
import java.util.Properties;

/**
 * @author xizizzz
 * @description: 消费者 自动提交
 * @date 2021-7-3上午 11:33
 */
public class MyConsumer {
    public static void main(String[] args) {
        //1. 创建消费者配置信息
        Properties props = new Properties();
        //2. 连接集群
        props.put("bootstrap.servers", "zookeeper1:9092");
        //3. 开启自动提交
        props.put("enable.auto.commit", "true");
        //4. 1秒提交一次
        props.put("auto.commit.interval.ms", "1000");
        //5. key value的反序列化
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        //6. 消费者组
        props.put("group.id", "xizi");
        // 重置消费者的offset
        // 1.1 换组生效
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        //7. 创建消费者
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
        //8. 订阅主题
        consumer.subscribe(Arrays.asList("aaa", "first"));
        //9. 获取数据
        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(100);
            for (ConsumerRecord<String, String> record : records) {
                System.out.printf("topic = %s,offset = %d, key = %s, value = %s%n", record.topic(), record.offset(), record.key(), record.value());
            }
        }
        //10. 关闭连接

    }
}
